<script lang="ts" setup>
import {useUserStore} from "@/stores/user";
import {onPullDownRefresh, onShow} from "@dcloudio/uni-app";
import {reactive, ref, watch} from "vue";
import type {UserDetail} from "@/types/user";
import {getUserDetailApi} from "@/api/user";
import {useBrowsingHistoryStore} from "@/stores/browsingHistory";
import {IMessage} from "@/components/aw-message/message"
import {getNewChatNumApi} from "@/api/chat";
import {useBadgeStore} from "@/stores/badgeNum";
// 获取顶部安全距离
const {safeAreaInsets} = uni.getSystemInfoSync()
const badgeStore = useBadgeStore();

interface CommonList {
  icon: string,
  color: string,
  badge: number,
  name: string
}


// 刷新
onPullDownRefresh(() => {
  if (!userStore.userInfoData?.userID) {
    return
  }
  networkError.value = false

  getUserDetail()
  uni.stopPullDownRefresh()

})

onShow(async () => {
  await getUserDetail()
  if (badgeStore.badge > 0) {
    uni.setTabBarBadge({
      index: 3,
      text: badgeStore.badge > 99 ? '99+' : badgeStore.badge.toString()
    })
  } else {
    uni.removeTabBarBadge({
      index: 3,
    })
  }
})


uni.$on('updateMyBadge', (msg: pushMessage) => {
  console.log('收到消息', badgeStore.badge, msg.increaseCount)
  iconList[2].badge = iconList[2].badge + msg.increaseCount!
  badgeStore.badge = iconList[2].badge + iconList[1].badge
})
//获取用户登录信息
const userStore = useUserStore()
//获取本地历史浏览
const browsingHistoryStore = useBrowsingHistoryStore()

// 进入加载用户详细信息
const userDetail = ref<UserDetail>()
const getUserDetail = async () => {
  if (!userStore.userInfoData?.token) {
    return
  }
  const res = await getUserDetailApi()
  if (res.code !== '1') {
    uni.showToast({
      title: res.message,
      icon: 'error'
    })
  }
  userDetail.value = res.data
  await getNewChatNum()
  iconList[2].badge = userDetail.value?.newLikedCount + userDetail.value?.newReplyCount + userDetail.value?.systemInfoCount + newChatNum.value
  iconList[1].badge = userDetail.value?.newUploadCount
  badgeStore.badge = iconList[2].badge + iconList[1].badge
}

const iconList = reactive<CommonList[]>([
  {
    icon: 'favor',
    color: 'yellow',
    badge: 0,
    name: '我的收藏'
  },
  {
    icon: 'edit',
    color: 'olive',
    badge: 0,
    name: '上传管理',
  },
  {
    icon: 'new',
    color: 'red',
    badge: 0,
    name: '消息中心',
  },
  {
    icon: 'friendfamous',
    color: 'orange',
    badge: 0,
    name: '我的粉丝',
  }
])
const iconOtherList = [
  {
    icon: 'friendadd',
    color: 'awGreen',
    badge: 0,
    name: '添加好友'
  },
  {
    icon: 'apps',
    color: 'awGreen',
    badge: 0,
    name: '关于应用'
  },
  {
    icon: 'mail',
    color: 'awGreen',
    badge: 0,
    name: '问题反馈',
  },
  // #ifdef MP-WEIXIN
  {
    icon: 'settings',
    color: 'awGreen',
    badge: 0,
    name: '设置',
  }
  // #endif
]

// 点击头像
const onClickAvatar = () => {
  // 没有登录
  if (!userStore.userInfoData) {
    return
  }
  // 登录后点击跳转详情页
  uni.navigateTo({url: '/subPkg/userHomepage/userHomepage?type=' + 0 + '&userId=' + userStore.userInfoData.userID})
}

// 点击登录
const goLogin = () => {
  if (userStore.userInfoData?.token) {
    return
  }
  uni.navigateTo({url: '/subPkg/login/login'})
}
//  点击设置
const goSetting = () => {
  uni.navigateTo({url: '/subPkg/setting/setting'})
}


/**
 * 点击工具栏
 * @param index 0-我的收藏
 * @param index 1-上传管理
 * @param index 2-收到的赞
 * @param index 3-主题切换
 */
const onClickTool = (index: number) => {
  if (!userStore.userInfoData?.token) return uni.showToast({title: '请先登录', icon: 'none', duration: 2000})
  if (index === 0) {
    uni.navigateTo({url: '/subPkg/collect/collect'})
  } else if (index === 1) {
    uni.navigateTo({url: '/subPkg/upload/upload'})
  } else if (index === 2) {
    uni.navigateTo({
      url: '/subPkg/message/message?' +
          'newLikedCount=' + userDetail.value?.newLikedCount +
          '&newReplyCount=' + userDetail.value?.newReplyCount +
          '&newSystemCount=' + userDetail.value?.systemInfoCount
    })
  } else if (index === 3) {
    uni.navigateTo({url: '/subPkg/FollowAndFansList/FollowAndFansList?type=' + 0 + '&userId=' + userStore.userInfoData.userID})
  }
}

// 点击去历史记录详情页
const goHistory = () => {
  uni.navigateTo({url: '/subPkg/userHistory/userHistory'})
}

const goDetail = (id: string) => {
  uni.navigateTo({url: '/subPkg/detail/detail?id=' + id})
}

const mPopup = ref()
/**
 * 点击其他功能
 * @param index 0——关于我们
 * @param index 1——问题反馈
 * @param  index 2——设置
 */
const onClickOther = (index: number) => {
  if (index === 0) {
    uni.navigateTo({url: '/subPkg/addFriends/addFriends'})
  } else if (index === 1) {
    uni.navigateTo({url: '/subPkg/aboutUs/aboutUs'})
  } else if (index === 2) {
    if (!userStore?.userInfoData?.token) {
      return uni.showToast({title: '请先登录后再使用该功能', icon: 'none', duration: 2000})
    }
    uni.navigateTo({url: '/subPkg/feedback/feedback'})
  } else if (index === 3) {
    uni.navigateTo({url: '/subPkg/setting/setting'})
  }
}

// 登陆/登出
const logout = () => {
  if (userStore?.userInfoData?.token) {
    mPopup.value.open()
  }
}
const onConfirmLogout = () => {
  // 删除本地信息
  userStore.clearUserInfo()
  userDetail.value = undefined
  iconList[2].badge = 0
  IMessage({
    content: '退出登录成功',
    showIcon: true,
    type: 'success'
  })
}
const networkError = ref(false)
uni.$on('noNetwork', () => {
  networkError.value = true
  uni.showToast({title: '网络异常，请稍检查网络', icon: 'none'})
  uni.stopPullDownRefresh()
})
watch(networkError, (value, oldValue) => {
  // 重新加载页面
  if (!value) {
    return uni.reLaunch({url: '/pages/my/my'})
  }
})
//头像加载错误
const avatarError = ref(false)
const handleAvatarError = () => {
  avatarError.value = true
}
const goLikeDetail = () => {
  uni.navigateTo({
    url: '/subPkg/message/messageList/messageList?title=' + '收到的赞' + '&type=' + 0
  })
}
const commentPopup = ref()
const goUploadDetail = () => {
  uni.navigateTo({url: '/subPkg/upload/upload'})
}

// 获取用户新收到的聊天信息
const newChatNum = ref(0)
const getNewChatNum = async () => {
  const res = await getNewChatNumApi()
  newChatNum.value = res.data
}

</script>
<template>
  <view v-if="userStore?.userInfoData?.userID" class="bg-gray">
    <!-- 顶部个人信息 -->
    <view :style="{ paddingTop: `${safeAreaInsets?.top}` + 'px'}" class="bg-white">
      <view class="flex padding" style="position: relative">
        <view class="bg-gray" style="overflow:hidden;border-radius: 25px">
          <uv-image
              :src="userStore.userInfoData?.avatarURL?userStore.userInfoData.avatarURL:'/static/kun.png'" height="50px"
              mode="aspectFill"
              radius="50%"
              width="50px" @click="onClickAvatar">
            <template v-slot:loading>
              <uv-image
                  :src="'/static/kun.png'" height="50px" mode="aspectFill"
                  radius="50%"
                  width="50px" @click="onClickAvatar"></uv-image>
            </template>
          </uv-image>
        </view>
        <view class="padding-xs text-lg text-black">
          <view style="margin-bottom: 3px" @click="goLogin">
            {{ userStore?.userInfoData ? userStore.userInfoData.username : '登录/注册' }}
          </view>
          <view class="cu-tag round  sm line-cyan3" style="color: #39c5bb">{{
              userStore.userInfoData
                  ? userStore?.userInfoData?.individualResume
                      ? userStore.userInfoData.individualResume?.slice(0, 15) : '这个人很懒，还什么都没写哟~'
                  : '请先登录'
            }}
          </view>
        </view>
        <!-- #ifndef MP-WEIXIN -->
        <uni-icons
            style="position: absolute; right: 4%;top: 50%;transform: translate(-50%,-50%);font-size: 56rpx; color: #39c5bb"
            type="gear"
            @click="goSetting">
        </uni-icons>
        <!-- #endif -->
      </view>
    </view>
    <!--    <uv-button @click="createMessage">创建通知</uv-button>-->
    <!-- 基本数据 -->
    <view class="cu-list grid col-3 no-border padding-lr-xs radius-lg-bottom">
      <view class="cu-item">
        <view class="text-black text-bold text-xl" @tap="commentPopup.open()">
          {{ userDetail?.commentCount || 0 }}
        </view>
        <text>评论</text>
      </view>
      <view class="cu-item">
        <view class="text-black text-bold text-xl" @tap="goLikeDetail">
          {{ userDetail?.likedCount || 0 }}
        </view>
        <text>获赞</text>
      </view>
      <view class="cu-item">
        <view class="text-black text-bold text-xl" @click="goUploadDetail">
          {{ userDetail?.uploadCount || 0 }}
        </view>
        <text>上传</text>
      </view>
    </view>
    <!-- 助力/推荐/邀请 -->
    <!--    <uv-button :color="'red'" @click="createMessage">创建消息</uv-button>-->
    <!--    <view class="margin-top-sm padding-lr-xs">
          <view class=" light radius-lg shadow-blur"
                style="background: linear-gradient(45deg,rgb(0,191,157,0.5),rgba(57,197,187,0.5),rgba(62,190,211,0.5))">
            <view class="flex padding-tb-sm padding-lr-sm justify-between">
              <view class="padding-xs">
                <view class="text-white">推荐给我的好友</view>
              </view>
              <view class="">
                <view class="cu-btn round text-white cuIcon-forwardfill"
                      style="background: linear-gradient(45deg,#f1f1f1 ,#39c5bb,#39c5bb,#3ebed3)">邀请好友
                </view>
              </view>
            </view>
          </view>
        </view>-->
    <!-- 常用功能 -->
    <view class="cu-bar margin-lr-xs margin-top-sm grid col-4 no-border bg-white radius-lg-top">
      <view class="action">
        <text class="text-lg text-black">常用功能</text>
      </view>
    </view>
    <view class="cu-list grid col-4 no-border text-black margin-lr-xs padding-bottom radius-lg-bottom">
      <view v-for="(item,index) in iconList" :key="index" :bindtap="item" class="cu-item"
            hover-class="hover-bg" style="transition: all 0.2s ease-in-out;"
            @click="onClickTool(index)">
        <view :class="['cuIcon-'+item.icon,'text-'+item.color,'text-shadow']" style="font-size: 56rpx;">
          <view v-if="item.badge>0" class="cu-tag badge">
            <block v-if="item.badge>0">{{ item.badge > 99 ? "99+" : item.badge }}</block>
          </view>
        </view>
        <text>{{ item.name }}</text>
      </view>
    </view>

    <!--   历史浏览 -->
    <view v-if="browsingHistoryStore.browsingHistory.length>0"
          class="cu-bar margin-lr-xs margin-top-sm grid col-4 no-border bg-white radius-lg-top">
      <view class="action">
        <text class="text-lg text-black ">浏览历史</text>
      </view>
      <text class="cuIcon-roundrightfill text-awGreen margin-right-sm" style="font-size: 18px"
            @click="goHistory"></text>
    </view>
    <view v-if="browsingHistoryStore.browsingHistory.length>0"
          class="col-4 cu-list grid margin-lr-xs no-border padding-bottom radius-lg-bottom text-black">
      <scroll-view :scroll-x="true" class="hot-panel" style="height: 120px">
        <view class="hot-box">
          <view v-for="(item,index) in browsingHistoryStore.browsingHistory.slice(0,20)" :key="item.id"
                class=" hot-item padding-top-xs" style="justify-content: stretch">
            <uv-image :mode="'aspectFill'" :src="item.imgURL" class="img" height="170rpx" radius="17rpx" width="250rpx"
                      @click="goDetail(item.id)">
              <template v-slot:loading>
                <view class="flex flex-column justify-center align-center padding-bottom-sm"
                      style="width: 100%;height: 100%;overflow: hidden">
                  <uv-image :src="'/static/home-selected.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
                  <text v-if="!item.imgURL" class="text-gray text-sm flex justify-center align-center " style="">
                    图片暂缺
                  </text>
                </view>
              </template>
            </uv-image>
            <text class="name padding-left-sm text-black" style="">{{ item.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 其他功能 -->
    <view class="cu-bar margin-lr-xs margin-top grid col-4 no-border bg-white radius-lg-top">
      <view class="action">
        <text class="text-lg">其他功能</text>
      </view>
    </view>
    <view class="cu-list grid col-4 no-border text-black margin-lr-xs padding-bottom radius-lg-bottom">
      <view v-for="(item,index) in iconOtherList" :key="index" :bindtap="item" class="cu-item"
            hover-class="hover-bg" style="transition: all 0.2s ease-in-out;"
            @click="onClickOther(index)">
        <view :class="['cuIcon-'+item.icon,'text-'+item.color,'text-shadow']" style="font-size: 56rpx;">
          <view v-if="item.badge!==0" class="cu-tag badge">
            <block v-if="item.badge!==1">{{ item.badge > 99 ? "99+" : item.badge }}</block>
          </view>
        </view>
        <text>{{ item.name }}</text>
      </view>
      <view v-if="userStore.userInfoData?.token" class="cu-item" hover-class="hover-bg"
            style="transition: all 0.2s ease-in-out;" @click="logout">
        <view class="cuIcon-exit text-awGreen text-shadow"
              style="font-size: 56rpx;"></view>
        <text>退出登录</text>
      </view>
    </view>
  </view>
  <view v-else class="flex flex-column justify-center align-center padding-lg"
        style="width: 100%;gap: 30px;min-height: 100vh">
    <view class="text-black text-bold text-xxl">登录即可体验完整功能</view>
    <button class="cu-btn bg-gradual-awGreen round text-lg" style="width: 150px;height: 40px" @click="goLogin">
      前往登录
    </button>
  </view>
  <!--  弹出层-->
  <uni-popup ref="mPopup" type="center">
    <uni-popup-dialog confirm-text="退出登录" content="确定要退出登录吗？" title="提示"
                      type="info" @confirm="onConfirmLogout">
    </uni-popup-dialog>
  </uni-popup>
  <uni-popup ref="commentPopup" type="dialog">
    <view class="bg-white padding-sm padding-top-lg flex flex-column"
          style="width: 300px;height: 180px;border-radius: 10px;overflow: hidden">
      <view class="text-gray flex-column flex align-center"
            style="width: 100%;flex:5;gap: 15px;border-bottom: #e6e6e6 1px solid">
        <text class="text-black text-xl">{{ userDetail?.username }}</text>
        <text class="text-sm">评论总数</text>
        <text class="text-awGreen text-xxl">{{ userDetail?.commentCount }}</text>
      </view>
      <view class="text-gray flex justify-center align-center padding-top-sm" style="width: 100%;flex: 1"
            @click="commentPopup.close()">知道了
      </view>
    </view>

  </uni-popup>
</template>

<style lang="scss">
page {
  overflow: hidden;
}

/* #ifdef H5 */
body {
  background-color: #f1f1f1;
}

/* #endif */

@import "@/pages/index/components/styles/hot.scss";
.hover-bg {
  background-color: #f2f2f2;
  border-radius: 10rpx;
  box-shadow: 0 0 10rpx #f1f1f1;
  // 动画效果从中心到外
  transition: all 0.2s ease-in-out;

}
</style>
